package com.diaohw.module.metadata.service.meta;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diaohw.module.metadata.mapper.MetaItemMapper;
import com.diaohw.module.metadata.obj.dto.MetaItemDTO;
import com.diaohw.module.metadata.obj.entity.MetaItemDO;
import com.diaohw.module.metadata.obj.query.MetaItemQuery;
import com.diaohw.module.metadata.obj.vo.MetaItemVO;
import com.diaohw.module.metadata.service.MetaItemService;
import com.diaohw.platform.common.obj.page.PageResultVo;
import com.diaohw.platform.framework.db.utils.WrapperUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 元数据属性 服务实现类
 * </p>
 *
 * @author D-Hw
 * @since 2025-04-07
 */
@Service
public class MetaItemImpl extends ServiceImpl<MetaItemMapper, MetaItemDO> implements MetaItemService {

    @Override
    public MetaItemVO create(MetaItemDTO data) {
        MetaItemDO model = INSTANCE.dtoToEntity(data);
        this.save(model);
        return INSTANCE.entityToVo(model);
    }

    @Override
    public MetaItemVO update(String id, MetaItemDTO data) {
        MetaItemDO model = INSTANCE.dtoToEntity(data);
        model.setId(id);
        this.updateById(model);
        return INSTANCE.entityToVo(model);
    }

    @Override
    public Boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    public MetaItemVO detail(String id) {
        MetaItemDO model = this.getById(id);
        return INSTANCE.entityToVo(model);
    }

    @Override
    public List<MetaItemVO> findByList(MetaItemQuery query) {
        LambdaQueryWrapper<MetaItemDO> wrapper = createWrapper(query);
        List<MetaItemDO> list = this.list(wrapper);
        return INSTANCE.entityToVo(list);
    }

    @Override
    public PageResultVo<MetaItemVO> findByPage(MetaItemQuery query) {
        LambdaQueryWrapper<MetaItemDO> wrapper = createWrapper(query);
        Page<MetaItemDO> page = this.page(WrapperUtils.createPage(query), wrapper);
        List<MetaItemVO> list = INSTANCE.entityToVo(page.getRecords());
        return PageResultVo.create(page.getTotal(), list);
    }

    private LambdaQueryWrapper<MetaItemDO> createWrapper(MetaItemQuery query) {
        LambdaQueryWrapper<MetaItemDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getItemName()), MetaItemDO::getItemName, query.getItemName());
        wrapper.eq(StrUtil.isNotBlank(query.getMetaId()), MetaItemDO::getMetaId, query.getMetaId());
        wrapper.eq(StrUtil.isNotBlank(query.getMetaCode()), MetaItemDO::getMetaCode, query.getMetaCode());
        return wrapper;
    }

}
